<template>
    <div>
        <el-card class="box-card">
            <template #header>
                <div class="card-header">
                    <el-button type="primary" size="default" @click="addTrademark" icon="Plus">添加品牌</el-button>
                </div>
            </template>
            <el-table v-model:data="trademarkList" border style="width: 100%">
                <el-table-column label="序号" width="150" type="index"></el-table-column>
                <el-table-column label="品牌名称" width="280" prop="tmName"></el-table-column>
                <el-table-column label="品牌LOGO">
                    <template #default="scope">
                        <img :src="scope.row.logoUrl" alt="" style="width: 100px;height: 100px;">
                    </template>
                </el-table-column>
                <el-table-column label="操作">
                    <template #default="scope">
                        <el-button type="primary" size="default" @click="handleEdit(scope.row)"
                            icon="Edit">编辑</el-button>
                        <el-popconfirm title="确定删除该品牌吗？" width="200px" @confirm="handleDelete(scope.row.id)">
                            <template #reference>
                                <el-button type="danger" size="default" icon="Delete">删除</el-button>
                            </template>
                        </el-popconfirm>
                    </template>
                </el-table-column>
            </el-table>
            <template #footer>
                <div class="demo-pagination-block">
                    <el-pagination v-model:current-page="nowPage" v-model:page-size="limit"
                        :page-sizes="[5, 10, 20, 30]" :background="true"
                        layout="sizes, prev, pager ,next, ->,jumper,total" v-model:total="total"
                        @current-change="handleTrademarkList" @size-change="handleSizeChange" />
                </div>
            </template>
        </el-card>
        <el-dialog v-model="dialogFormVisible" :title="trademarkInfo.id ? '编辑品牌' : '添加品牌'" width="500">
            <el-form :rules="rules" :model="trademarkInfo" ref="trademarkFormRef">
                <el-form-item label="品牌名称" label-width="100px" prop="tmName">
                    <el-input autocomplete="off" placeholder="请输入品牌名称" v-model="trademarkInfo.tmName" />
                </el-form-item>
                <el-form-item label="品牌LOGO" label-width="100px" prop="logoUrl">
                    <el-upload class="avatar-uploader" action="/api/admin/product/fileUpload" :show-file-list="false"
                        :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
                        <img v-if="trademarkInfo.logoUrl" :src="trademarkInfo.logoUrl" class="avatar" />
                        <el-icon v-else class="avatar-uploader-icon">
                            <Plus />
                        </el-icon>
                    </el-upload>
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="handleAddCancel">取消</el-button>
                    <el-button type="primary" @click="handleAddOrUpdateConfirm">
                        确定
                    </el-button>
                </div>
            </template>
        </el-dialog>
    </div>

</template>

<script setup lang="ts">
import { addTrademarkOrUpdate, deleteTrademark, getTrademarkList } from '@/api/product/trademark';
import type { Trademark, TrademarkListResponse } from '@/api/product/trademark/type';
import { useThrottle } from '@/utils/throttle';
import { useDebounce } from '@/utils/debounce';
import { ElMessage, type UploadProps } from 'element-plus';
import { onMounted, reactive, ref } from 'vue';
// 当前页
let nowPage = ref(1);
// 每页条数
let limit = ref(5);
// 总条数
let total = ref(0);
// 品牌列表
let trademarkList = ref<Trademark[]>([]);
// 弹窗flag
let dialogFormVisible = ref(false);
//新增品牌信息
let trademarkInfo = reactive<Trademark>({
    tmName: '',
    logoUrl: ''
})
// 表单ref
let trademarkFormRef = ref();
// 获取品牌列表
const handleTrademarkList = useDebounce(async () => {
    const res: TrademarkListResponse = await getTrademarkList(nowPage.value, limit.value);
    total.value = res.data.total;
    trademarkList.value = res.data.records;
}, 1000)
onMounted(() => {
    handleTrademarkList();
})
// 调整每页条数
const handleSizeChange = () => {
    nowPage.value = 1;
    handleTrademarkList();
}
// 添加品牌按钮回调
const addTrademark = () => {
    dialogFormVisible.value = true;
    // 清空表单
    trademarkInfo.tmName = '';
    trademarkInfo.logoUrl = '';
    trademarkInfo.id = undefined;
    // 清空校验信息
    trademarkFormRef?.value.clearValidate();
}
// 上传前
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
    if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png') {
        ElMessage.error('Avatar picture must be JPG or PNG format!')
        return false
    } else if (rawFile.size / 1024 / 1024 > 2) {
        ElMessage.error('Avatar picture size can not exceed 2MB!')
        return false
    }
    return true
}
// 上传成功
const handleAvatarSuccess: UploadProps['onSuccess'] = (response, _uploadFile) => {
    //response是上传图片之后后端返回的数据
    trademarkInfo.logoUrl = response.data;
    trademarkFormRef.value.clearValidate('logoUrl');
}
// 取消
const handleAddCancel = () => {
    dialogFormVisible.value = false;
    // 清空表单
    trademarkInfo.tmName = '';
    trademarkInfo.logoUrl = '';
}
// 添加或者修改的确定
const handleAddOrUpdateConfirm = useThrottle(async () => {
    const valid = await trademarkFormRef.value.validate();
    console.log(valid);
    try {
        const res = await addTrademarkOrUpdate(trademarkInfo);
        console.log(res);
        if (res.code == 200) {
            ElMessage.success({ type: 'success', message: trademarkInfo.id ? '编辑品牌成功' : '添加品牌成功' });
            // 重新获取品牌列表
            handleTrademarkList();
            // 关闭弹窗
            dialogFormVisible.value = false;
            // 清空表单
            trademarkInfo.tmName = '';
            trademarkInfo.logoUrl = '';
            trademarkInfo.id = trademarkInfo.id ? trademarkInfo.id : undefined;
        } else {
            console.log(res);
            ElMessage.error({ type: 'error', message: trademarkInfo.id ? '编辑品牌失败a' : '添加品牌失败' });
        }
    } catch (error) {
        console.log(error);
        ElMessage.error({ type: 'error', message: trademarkInfo.id ? '编辑品牌失败' : '添加品牌失败 ' + error as string });
    }

}, 1000)
// 编辑修改
const handleEdit = (row: Trademark) => {
    // 将row中的数据赋值给trademarkInfo
    trademarkInfo.logoUrl = row.logoUrl;
    trademarkInfo.tmName = row.tmName;
    trademarkInfo.id = row.id;
    dialogFormVisible.value = true;
    // 清空校验信息
    trademarkFormRef?.value.clearValidate();
}
// 删除品牌
const handleDelete = useThrottle(async (id: number) => {
    try {
        const res = await deleteTrademark(id);
        if (res.code == 200) {
            ElMessage.success('删除品牌成功');
            //重新获取品牌列表
            handleTrademarkList();
        } else {
            ElMessage.error(res.data);
        }
    } catch (error) {
        console.log(error);
        ElMessage.error('删除品牌失败');
    }
}, 1000)
// 品牌名称校验
const validateTmName = (_rule: any, value: any, callback: any) => {
    if (value == '') {
        callback(new Error('品牌名称不能为空'));
    } else if (value.length < 2 || value.length > 10) {
        callback(new Error('品牌名称长度在2-10个字符之间'));
    } else {
        callback();
    }
}
// 品牌LOGO校验
const validateLogoUrl = (_rule: any, value: any, callback: any) => {
    if (value == '') {
        callback(new Error('品牌LOGO不能为空'));
    } else {
        callback();
    }
}
//表单校验规则
const rules = reactive({
    tmName: [
        { required: true, trigger: 'blur', validator: validateTmName },
    ],
    logoUrl: [
        { required: true, trigger: 'blur', validator: validateLogoUrl }
    ]
})

</script>
<style scoped lang="less">
@import '../../../styles/product/trademark.less';
</style>
